from django.db import models

# 自定义字段类型
class MyChar(models.Field):
    def __init__(self, *args, **kwargs):
        self.max_length = kwargs['max_length']
        super().__init__( *args, **kwargs)

    def db_type(self, connection):
        return f"char({self.max_length})"


class SmallintField(models.Field):
    def db_type(self, connection):
        return 'smallint'


class TinyintField(models.Field):
    def db_type(self, connection):
        return 'tinyint'


class User(models.Model):
    # phonenum = models.CharField(max_length=11, unique=True, verbose_name="手机号")
    phonenum = MyChar(max_length=11)
    nickname = models.CharField(max_length=20, verbose_name="昵称")
    # male男, female女
    sex = models.CharField(max_length=10, default="male", verbose_name="性别")
    # birth_year = models.IntegerField(default=2002, verbose_name="出生年")
    birth_year = SmallintField(default=2002, verbose_name="出生年")
    birth_month = TinyintField(default=1, verbose_name="出生月")
    birth_day = TinyintField(default=1, verbose_name="出生日")
    avatar = models.CharField(max_length=100, default='', verbose_name="个人形象")
    location = models.CharField(max_length=20, default="北京", verbose_name="常居地")
    vip_id = models.IntegerField(default=1)

    class Meta:
        db_table = 'sp_user'

    @property
    def profile(self):
        # 先判断 当前 用户对象中 有没有 obj 属性
        # 如果没有的话,就把 查询到的结果 赋值 给 obj属性
        # 如果有这个属性,就直接返回
        if not hasattr(self, 'obj'):
            self.obj, _ = Profile.objects.get_or_create(id=self.id)

        return self.obj


    def __str__(self):
        return str(self.id)


class Profile(models.Model):
    location = models.CharField(max_length=100, verbose_name="目标城市")
    min_distance = models.IntegerField(default=1, verbose_name="最小查找范围")
    max_distance = models.IntegerField(default=10, verbose_name="最大查找范围")
    min_dating_age = models.IntegerField(default=18, verbose_name="最小交友年龄")
    max_dating_age = models.IntegerField(default=60, verbose_name="最大交友年龄")
    dating_sex = models.CharField(max_length=20, default="male",verbose_name="匹配的性别")

    class Meta:
        db_table = "sp_profile"